Import mojo
Import timelinefx

Class ray extends App

	Field box:tlBox
	Field poly:tlPolygon
	Field line:tlLine
	Field circle:tlCircle
	
	Field ray:tlVector2 = New tlVector2(0, 0)
	Field result:tlCollisionResult = New tlCollisionResult
	Field point:tlVector2 = New tlVector2(0, 0)
	
	Field shape:Int

	Method OnCreate()
		box = new tlBox(400, 300, 100, 100)
		Local verts:Float[] =[-100.0, 0.0, -150.0, 100.0, 50.0, 150.0, 185.0, 100.0, 300.0, 0.0]
		poly = New tlPolygon(400, 200, verts)
		line = New tlLine(200, 500, 800, 100)
		circle = New tlCircle(400, 300, 40)
		
		SetUpdateRate 60
	End
	
	Method OnUpdate()
		'set the ray vector based on the point->mouse vector
		If MouseDown(0) point.SetPosition(MouseX(), MouseY())
		ray.SetPosition(MouseX() - point.x, MouseY() - point.y)
		
		'normalise the ray so we can draw the laser a fixed length a bit more easily
		ray.Normalise()
		
		'iterate through shapes if space is pressed
		If KeyHit(KEY_SPACE)
			shape+=1
			If shape > 3 shape = 0
		End If
		
		'do a ray collision checked on the selected shape and store the result
		Select shape
			Case 0
				result = CheckRayCollision(box, point.x, point.y, ray.x, ray.y)
			Case 1
				line.Rotate(1)
				result = CheckRayCollision(line, point.x, point.y, ray.x, ray.y)
			Case 2
				result = CheckRayCollision(circle, point.x, point.y, ray.x, ray.y)
			Case 3
				poly.Rotate(1)
				result = CheckRayCollision(poly, point.x, point.y, ray.x, ray.y)
		End Select
	End
	
	Method OnRender()
		Cls
		Select shape
			Case 0
				box.Draw
			Case 1
				line.Draw
			Case 2
				circle.Draw
			Case 3
				poly.Draw
				DrawText(poly.angle, 10, 40)
		End Select
		SetColor 255, 0, 0
		DrawRect point.x - 5, point.y - 5, 10, 10
		
		'if the result shows an intersection and it wasn't insise the shape
		If result.RayIntersection And Not result.RayOriginInside
			'draw the ray upto the intersection point
			DrawLine point.x, point.y, result.rayintersection.x, result.rayintersection.y
			DrawOval result.rayintersection.x - 4, result.rayintersection.y - 4, 8, 8
			'find the rebound vector
			Local rebound:tlVector2 = result.GetReboundVector(ray)
			'draw the rebounded ray
			DrawLine result.rayintersection.x, result.rayintersection.y,
					result.rayintersection.x + rebound.x * 500, result.rayintersection.y + rebound.y * 500
		ElseIf result.RayOriginInside
			DrawText "Ray starts inside object!", 10, 30
		Else
			'no intersection, draw a line for the ray
			DrawLine point.x, point.y, point.x + ray.x * 1000, point.y + ray.y * 1000
		EndIf
		
		DrawText "Press space to change shape", 10, 10
		DrawText "Click and drag to move the laser origin", 10, 20

	End
End

Function Main()
	New ray
	
End

